﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SmartParking.Web.UC
{
    public partial class Schedule : System.Web.UI.UserControl
    {
        private DateTime _StartDate;
        private bool _StartDateSetOnEvent;

        public Int32 ParkingZoneID
        {
            set
            {
                ViewState["ParkingZoneID"] = value;
            }
            get
            {
                return Convert.ToInt32(ViewState["ParkingZoneID"]);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack || _StartDateSetOnEvent)
            {
                if (_StartDate == new DateTime())
                {
                    _StartDate = DateTime.UtcNow.AddDays(Convert.ToInt32(DateTime.UtcNow.DayOfWeek) * -1);
                }

                HttpCookie startDateCookie = new HttpCookie("SmartParkingSchedule", _StartDate.ToString());
                startDateCookie.Expires = DateTime.UtcNow.AddMinutes(5);
                Response.Cookies.Add(startDateCookie);
                lbCurrentWeek.Text = String.Format("{0} - {1}", new Object[] { _StartDate.ToString("MMMM dd, yyyy"), _StartDate.AddDays(6).ToString("MMMM dd, yyyy") });                
            }
            else
                _StartDate = Convert.ToDateTime(Request.Cookies["SmartParkingSchedule"].Value);

            Refresh();
        }

        private void Refresh()
        {
            if (ParkingZoneID != 0)
            {
                Bussiness.Schedule schedule = new Bussiness.Schedule(Application, Profile.ManagerID, _StartDate);
                _StartDate = schedule.StartDate;
                System.Data.DataTable info = schedule.Refresh(ParkingZoneID);
                grdSchedule.DataSource = info;
                grdSchedule.DataBind();
            }
        }

        protected void grdSchedule_DataBound(object sender, EventArgs e)
        {
            // Update Column Headers Text
            if (grdSchedule.HeaderRow != null)
            {
                for (int i = 1; i < 8; i++)
                    grdSchedule.HeaderRow.Cells[i].Text = _StartDate.AddDays(i - 1).ToString("ddd dd");
            }
        }

        protected void lbtnPrevious_Click(object sender, EventArgs e)
        {
            _StartDate = _StartDate.AddDays(-7);
            _StartDateSetOnEvent = true;
            Page_Load(sender, e);
        }
        
        protected void lbtnNext_Click(object sender, EventArgs e)
        {
            _StartDate = _StartDate.AddDays(7);
            _StartDateSetOnEvent = true;
            Page_Load(sender, e);
        }
    }
}
